package com.handong.handserialprogram.module.createmission.recordtask;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.module.base.SimpleFragment;
import com.handong.handserialprogram.module.createmission.CreateMissionActivity;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SearchFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SearchFragment extends SimpleFragment implements SearchAdapter.AddListener {

    private static final String TAG = SearchFragment.class.getSimpleName();
    private static final String PERSON_TYPE = "person_type";

    private int mPersonType;

    private TextView mSearchAction, mSearchType;
    private AppCompatEditText mInputMessage;
    private AppCompatImageView mInputClear;

    private RecyclerView mSearchResult;
    private SearchAdapter mSearchAdapter;
    private LinearLayout mLoadingLayout;

    private List<PersonEntity> mPersonList;

    public SearchFragment() {
    }

    public static SearchFragment newInstance(List<PersonEntity> list, boolean isCriminal) {
        SearchFragment fragment = new SearchFragment();
        fragment.mPersonList = list;
        Bundle args = new Bundle();
        args.putBoolean(PERSON_TYPE, isCriminal);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            if (bundle.getBoolean(PERSON_TYPE, false)) {
                mPersonType = CriminalFragment.TYPE_CRIMINAL;
            } else {
                mPersonType = CriminalFragment.TYPE_POLICE;
            }
        }
    }

    @Override
    protected int getContentViewID() {
        return R.layout.fragment_search;
    }

    @Override
    protected void initViewByID(View contentView) {
        mSearchAction = (TextView) contentView.findViewById(R.id.personSearchAction);
        mInputClear = (AppCompatImageView) contentView.findViewById(R.id.searchInputClear);
        mInputMessage = (AppCompatEditText) contentView.findViewById(R.id.searchInputMsg);
        mSearchType = (TextView) contentView.findViewById(R.id.personSearchType);
        mLoadingLayout = (LinearLayout) contentView.findViewById(R.id.dialogLoadingLayout);
        mSearchResult = (RecyclerView) contentView.findViewById(R.id.searchPersonResult);
    }

    @Override
    protected void initViewData() {
        ViewUtil.closeDefaultAnimator(mSearchResult);
        mSearchType.setText(mPersonType == CriminalFragment.TYPE_CRIMINAL ?
                R.string.record_task_criminal : R.string.record_task_police);
        mSearchAction.setOnClickListener(this);
        mInputClear.setOnClickListener(this);
        mInputMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    mInputClear.setVisibility(View.VISIBLE);
                } else {
                    mInputClear.setVisibility(View.GONE);
                }
            }
        });
        ViewUtil.changeEditTextStatus(mInputMessage);
        mInputMessage.requestFocus();
        AppUtil.showSoftInput(mInputMessage);
    }

    @Override
    public void onClick(View v) {
        if (dispatchDoubleClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.searchInputClear:
                mInputMessage.setText("");
                break;
            case R.id.personSearchAction:
                searchKeyWords(mInputMessage.getText().toString().trim());
                break;
            default:
                super.onClick(v);
        }
    }

    private void searchKeyWords(String key) {
        if (TextUtils.isEmpty(key)) {
            AppUtil.showShortToast(getActivity(), "请输入关键字");
            return;
        }
        AppUtil.hideSoftInput(getActivity(), getActivity().getWindow());
        mSearchResult.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.VISIBLE);
        List<PersonEntity> list = new ArrayList<>();
        PersonEntity entity = null;
//        for (int i = 0; i < 20; i++) {
//            entity = new PersonEntity();
//            entity.setName("抢劫犯-朱林 " + i);
//            entity.setId("00" + i);
//            list.add(entity);
//        }
        showSearchResult(list);
    }

    private void showSearchResult(List<PersonEntity> list) {
        //标记已添加人员。
        int limit = mPersonList.size();
        int flag = 0;
        List<PersonEntity> tempList = mPersonList;
        for (PersonEntity temp : list) {
            if (flag < limit && tempList.contains(temp)) {
                temp.setChecked(true);
                flag++;
            }
        }
        if (mSearchAdapter == null) {
            mSearchAdapter = new SearchAdapter(list, this, true);
            mSearchResult.setLayoutManager(new LinearLayoutManager(getContext().getApplicationContext()));
            mSearchResult.setAdapter(mSearchAdapter);
        } else {
            mSearchAdapter.notifyDataSetChanged();
        }
        mLoadingLayout.setVisibility(View.GONE);
        mSearchResult.setVisibility(View.VISIBLE);
    }

    @Override
    public void addSearchPerson(PersonEntity entity, int position) {
        entity.setChecked(true);
        mSearchAdapter.notifyItemChanged(position);
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        activity.addSearchPerson(entity);
        JLog.d(TAG, entity.toString());
    }

    @Override
    protected boolean onBackClicked() {
        removeFrag(this, R.anim.anim_no, R.anim.slide_bottom_out);
        return true;
    }
}
